export default class PrintPreview {
  /**
   * @param {string} containerId - 预览容器元素ID
   * @param {Object} options - 配置选项
   */
  constructor(containerId, options = {}) {
    this.containerId = containerId;
    this.options = {
      maxPageHeightPx: options.maxPageHeightPx || 1100, // A4纸高度约1122px，留点边距
      ...options
    };
    this.isProcessed = false;
  }

  /**
   * 渲染预览内容（不分页）
   */
  async renderPreview(data, templateFunction) {
    try {
      const container = document.getElementById(this.containerId);
      if (!container) {
        console.error(`未找到容器 ID: ${this.containerId}`);
        return false;
      }

      const htmlContent = templateFunction(data);
      container.innerHTML = htmlContent;
      console.log('预览内容已渲染（未分页）');

      this.isProcessed = false;
      return true;
    } catch (error) {
      console.error('渲染预览失败:', error);
      return false;
    }
  }

  /**
   * 在模态框显示后进行分页处理
   */
  async processPagination() {
    try {
      if (this.isProcessed) {
        console.log('已经处理过分页，跳过');
        return true;
      }

      console.log('开始分页处理...');
      await this.waitForModal();

      const container = document.getElementById(this.containerId);
      if (!container) {
        console.error(`未找到容器 ID: ${this.containerId}`);
        return false;
      }

      const success = this.calculateAndApplyPagination(container);
      
      if (success) {
        this.isProcessed = true;
        console.log('分页处理完成');
      }

      return success;
    } catch (error) {
      console.error('分页处理失败:', error);
      return false;
    }
  }

  waitForModal() {
    return new Promise(resolve => {
      setTimeout(resolve, 300);
    });
  }

  /**
   * 计算并应用分页
   */
  calculateAndApplyPagination(container) {
    const printElement = container.querySelector('.sn-sltrpigstmt-bill-print');
    if (!printElement) {
      console.warn('未找到可打印元素');
      return false;
    }

    const table = printElement.querySelector('table');
    if (!table) {
      console.warn('未找到table元素');
      return false;
    }

    const tbody = table.querySelector('tbody');
    if (!tbody) {
      console.warn('未找到tbody元素');
      return false;
    }

    // 获取所有tr元素
    const allRows = Array.from(tbody.children).filter(row => {
      return row.tagName === 'TR';
    });

    if (allRows.length === 0) {
      console.warn('没有找到数据行');
      return false;
    }

    console.log(`总共 ${allRows.length} 行数据，页面最大高度: ${this.options.maxPageHeightPx}px`);

    // 测量每一行的实际高度
    const rowHeights = this.measureRowHeights(allRows);

    // 检查是否所有高度都为0
    const validHeights = rowHeights.filter(height => height > 0);
    if (validHeights.length === 0) {
      console.error('所有行高度都为0，无法进行分页计算');
      return false;
    }

    // 根据高度计算分页
    const pages = this.calculatePagination(allRows, rowHeights);

    if (pages.length > 1) {
      console.log(`需要分成 ${pages.length} 页`);
      this.applyPagination(printElement, pages);
      return true;
    } else {
      console.log('数据量较少，不需要分页');
      return true;
    }
  }

  /**
   * 测量每行实际高度并强制设置固定高度
   */
  measureRowHeights(rows) {
    const heights = [];
    
    rows.forEach((row, index) => {
      // 获取实际渲染高度
      const height = row.offsetHeight;
      heights.push(height);
      console.log(`第 ${index + 1} 行高度: ${height}px`);
      
      // 强制设置行高度，防止打印时自动撑高
      row.style.height = height + 'px';
      row.style.minHeight = height + 'px';
      row.style.maxHeight = height + 'px';
      
      // 同时设置单元格高度
      const cells = row.querySelectorAll('td');
      cells.forEach(cell => {
        cell.style.height = height + 'px';
        cell.style.minHeight = height + 'px';
        cell.style.maxHeight = height + 'px';
        cell.style.verticalAlign = 'center'; // 确保内容顶对齐
        cell.style.overflow = 'hidden'; // 防止内容溢出
      });
    });

    return heights;
  }

  /**
   * 根据实际高度计算分页
   */
  calculatePagination(allRows, rowHeights) {
    const pages = [];
    let currentPage = [];
    let currentPageHeight = 0;

    console.log(`每页最大高度: ${this.options.maxPageHeightPx}px`);

    for (let i = 0; i < allRows.length; i++) {
      const rowHeight = rowHeights[i] || 40; // 默认行高
      
      // 检查添加当前行后是否超过页面高度限制
      if (currentPage.length > 0 && (currentPageHeight + rowHeight) > this.options.maxPageHeightPx) {
        console.log(`第 ${pages.length + 1} 页完成: ${currentPage.length} 行, 高度 ${currentPageHeight}px`);
        pages.push({
          rows: [...currentPage],
          totalHeight: currentPageHeight
        });
        
        // 开始新页
        currentPage = [allRows[i]];
        currentPageHeight = rowHeight;
      } else {
        // 添加到当前页
        currentPage.push(allRows[i]);
        currentPageHeight += rowHeight;
      }
    }

    // 添加最后一页
    if (currentPage.length > 0) {
      console.log(`最后一页: ${currentPage.length} 行, 高度 ${currentPageHeight}px`);
      pages.push({
        rows: currentPage,
        totalHeight: currentPageHeight
      });
    }

    return pages;
  }

  /**
   * 应用分页到预览界面
   */
  applyPagination(originalElement, pages) {
    // 保存原始结构
    const printHead = originalElement.querySelector('.print-head');
    const printFooter = originalElement.querySelector('.print-footer');
    const originalTable = originalElement.querySelector('table');
    
    if (!originalTable) {
      console.error('未找到table元素');
      return;
    }

    const tableHead = originalTable.querySelector('thead');
    const tableFoot = originalTable.querySelector('tfoot');

    // 构建分页HTML
    let paginatedHtml = '';
    
    for (let pageNum = 0; pageNum < pages.length; pageNum++) {
      const page = pages[pageNum];
      
      console.log(`构建第 ${pageNum + 1} 页，包含 ${page.rows.length} 行`);
      
      // 每页都添加分页标识（包括最后一页）
      // if (pageNum > 0) {
      //   paginatedHtml += `
      //     <div style="page-break-before: always; height: 30px; border-bottom: 2px dashed #ccc; margin: 20px 0; text-align: center; color: #666; font-size: 14px; background-color: #f9f9f9; line-height: 30px;">
      //       --- 第${pageNum + 1}页 ---
      //     </div>
      //   `;
      // }
      
      // 页眉（每页都有）
      let pageHeadHtml = '';
      if (printHead) {
        pageHeadHtml = printHead.outerHTML;
      }
      
      // 表格内容
      let tableBodyHtml = '';
      page.rows.forEach(row => {
        tableBodyHtml += row.outerHTML;
      });
      
      // 表格合计（仅最后一页）
      let tableFootHtml = '';
      if (pageNum === pages.length - 1 && tableFoot) {
        tableFootHtml = tableFoot.outerHTML;
      }
      
      // 页脚（仅最后一页）
      let footerHtml = '';
      if (pageNum === pages.length - 1 && printFooter) {
        footerHtml = printFooter.outerHTML;
      }
      
      // 构建单页内容
      paginatedHtml += `
        <div class="sn-sltrpigstmt-bill-print" style="position: relative; color: black; min-height: ${this.options.maxPageHeightPx}px; margin-bottom: 40px; page-break-inside: avoid; border: 1px solid #eee; padding: 10px;">
          <div style="margin-left: 0px; font-size: 18px; margin-right: 10px;">
            ${pageHeadHtml}
            <div style="display: flex; margin-left: 0px;">
              <table style="width: 100%; color: black;" class="printTable">
                ${tableHead ? tableHead.outerHTML : ''}
                <tbody>
                  ${tableBodyHtml}
                </tbody>
                ${tableFootHtml}
              </table>
            </div>
            ${footerHtml}
          </div>
        </div>
      `;
    }
    
    // 在最后添加结束标识
    // if (pages.length > 1) {
    //   paginatedHtml += `
    //     <div style="height: 20px; margin: 20px 0; text-align: center; color: #999; font-size: 12px;">
    //       --- 共${pages.length}页 完 ---
    //     </div>
    //   `;
    // }
    
    // 替换原始预览内容
    originalElement.outerHTML = paginatedHtml;
    
    console.log(`分页完成，共生成 ${pages.length} 页`);
  }


  /**
   * 重置状态
   */
  reset() {
    this.isProcessed = false;
  }

  /**
   * 静态方法：渲染预览
   */
  static async render(containerId, data, templateFunction, options = {}) {
    const preview = new PrintPreview(containerId, options);
    const success = await preview.renderPreview(data, templateFunction);
    
    if (success) {
      return preview;
    } else {
      throw new Error('预览渲染失败');
    }
  }
}